﻿using MapEditor.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Shapes;

namespace MapEditor.MapService
{
    public class MapService
    {
        public static double MapWidth { get; set; }
        public static double MapHeight { get; set; }

        public static string MapFilePath { get; set; }

        //private static List<System.Windows.Shapes.Rectangle> Rectangles = null;
        public static QuadTree QuadTree = null;


        public static void CreateGameMap(List<MapGameItem> MapObjects, string FilePath)
        {
            getQuadTree(MapObjects, true);
            CreateGameMapFromCurrentQuadTree(FilePath);
        }

        /// <summary>
        /// Get quadtree from rectangle object
        /// </summary>
        /// <returns></returns>
        private static QuadTree getQuadTree(List<MapGameItem> MapObjects, bool isNew)
        {
            if (QuadTree == null || isNew)
            {
                if (MapObjects != null)
                {
                    int id = 0;
                    QuadTree = new QuadTree(MapService.MapWidth, MapService.MapHeight);
                    foreach (MapGameItem item in MapObjects)
                    {
                        QuadTree.AddObject(createGameObject(id++, item.Type, item.Rectangle));
                    }
                }
            }

            return QuadTree;
        }

        /// <summary>
        /// Create gameobject from rectangle in map
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="Rectangle"></param>
        /// <returns>gameobject in real world</returns>
        private static GameObject createGameObject(int Id, int Type, System.Windows.Shapes.Rectangle Rectangle)
        {
            GameObject obj = GameObject.createGameObject(Id, Rectangle, 0, 0, Type);
            //convert to real position
            obj.Rect.Y = MapService.MapHeight - obj.Rect.Y;

            return obj;
        }

        /// <summary>
        /// Create map file from quadtree
        /// </summary>
        /// <param name="FilePath"></param>
        private static void CreateGameMapFromCurrentQuadTree(string FilePath)
        {
            string contentToWrite = "";
            QuadTree.serialize(ref contentToWrite);

            System.IO.File.WriteAllText(FilePath, contentToWrite.Replace("\n", Environment.NewLine));

        }
        
    }
}
